package com.ziq.zcamp.place

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.GsonUtils
import com.ziq.base.extension.launchWithTry
import com.ziq.base.extension.launchWithTryAsynchronous
import com.ziq.base.manager.MMKVManager
import com.ziq.zcamp.R
import com.ziq.zcamp.api.request.camp.AllCityListParam
import com.ziq.zcamp.api.request.camp.CampConditionTreeParam
import com.ziq.zcamp.api.request.camp.CampHotConditionListParam
import com.ziq.zcamp.api.respond.camp.AllAreaListRespond
import com.ziq.zcamp.api.respond.camp.CampConditionTree
import com.ziq.zcamp.api.respond.camp.CampListConditionListRespond
import com.ziq.zcamp.api.service.CampService
import com.ziq.zcamp.api.service.request
import com.ziq.zcamp.bean.place.*
import com.ziq.zcamp.constant.KEY_HISTORY_CITY
import com.ziq.zcamp.manager.GlobalContextManager
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class CampListAreaViewModel @Inject constructor() : ViewModel() {

    companion object {
        val wholeCountry = AreaItem(-1L, GlobalContextManager.getString(R.string.whole_country), -1)
    }

    @Inject
    lateinit var mCampService: CampService

    val historyCityList = MutableLiveData<CityList>()
    val areaData = MutableLiveData<AreaData>()

    val filterAreaData = MutableLiveData<FilterAreaData>()
    val filterConditionData = MutableLiveData<List<CampConditionTree>>()
    val hotConditionData = MutableLiveData<List<CampHotConditionItem>>()



    init {

        try {
            val historyCityString = MMKVManager.mmkv.decodeString(KEY_HISTORY_CITY, "")
            val item = GsonUtils.fromJson(historyCityString, CityList::class.java)
            if(item != null){
                historyCityList.value = item!!
                val tempFilterAreaData = filterAreaData.value?:FilterAreaData()
                tempFilterAreaData.historyList = item.list ?: mutableListOf()
                filterAreaData.value = tempFilterAreaData
            }
            filterConditionData.value = mutableListOf(
                CampConditionTree().apply {
                    id = 1
                    name = "类型"
                    pictures = "[{\"height\":111,\"status\":2,\"url\":\"${"res://drawable/" + R.drawable.icon_camp_list_filter_type}\",\"width\":129}]"
                },
                CampConditionTree().apply {
                    id = 2
                    name = "环境"
                    pictures = "[{\"height\":111,\"status\":2,\"url\":\"${"res://drawable/" + R.drawable.icon_camp_list_filter_env}\",\"width\":129}]"
                },
                CampConditionTree().apply {
                    id = 3
                    name = "配套"
                    pictures = "[{\"height\":111,\"status\":2,\"url\":\"${"res://drawable/" + R.drawable.icon_camp_list_filter_support}\",\"width\":129}]"
                },
            )
        }catch (e:Exception){}

    }

    fun findTargetArea(adcode:String):AreaItem?{
        if(adcode.isNotEmpty() && adcode.length > 4){
            val provinceCode = adcode.substring(0, 2)
            val cityCode = adcode.substring(0, 4)
            if(filterAreaData.value?.provinces?.isNotEmpty() == true){
                for (item in filterAreaData.value?.provinces!!){
                    if((item.ad_code?.length?:0) > 2 && item.ad_code?.substring(0, 2) == provinceCode){
                        return item
                    }
                }
            }
            if(filterAreaData.value?.cities?.isNotEmpty() == true){
                for (item in filterAreaData.value?.cities!!){
                    if((item.ad_code?.length?:0) > 4 && item.ad_code?.substring(0, 4) == cityCode){
                        return item
                    }
                }
            }
        }
        return null
    }

    fun findTargetArea(id:Long?):AreaItem?{
        if(id != null){
            if(filterAreaData.value?.provinces?.isNotEmpty() == true){
                for (item in filterAreaData.value?.provinces!!){
                    if(item.id == id){
                        return item
                    }
                }
            }
            if(filterAreaData.value?.cities?.isNotEmpty() == true){
                for (item in filterAreaData.value?.cities!!){
                    if(item.id == id){
                        return item
                    }
                }
            }
        }
        return null
    }

    val historyLimit = 6
    fun updateHistoryCityByClick(clickItem : AreaItem?){
        val tempCityList = CityList()
        val tempHistoryList = mutableListOf<AreaItem>()
        if(historyCityList.value != null && historyCityList.value!!.list != null){
            for (item in historyCityList.value!!.list!!){
                if(item.id != clickItem?.id){
                    tempHistoryList.add(item)
                }
            }
        }

        if(clickItem?.id != wholeCountry.id && clickItem != null){
            tempHistoryList.add(0, clickItem)
        }

        if (tempHistoryList.size > historyLimit){
            tempCityList.list = tempHistoryList.subList(0, historyLimit)
        } else {
            tempCityList.list = tempHistoryList
        }


        historyCityList.postValue(tempCityList)

        val tempFilterAreaData = filterAreaData.value?:FilterAreaData()
        tempFilterAreaData.historyList = tempCityList.list ?: mutableListOf()
        filterAreaData.postValue(tempFilterAreaData)

        try {
            MMKVManager.mmkv.encode(KEY_HISTORY_CITY, GsonUtils.toJson(tempCityList))
        }catch (e:Exception){}
    }

    fun requestAreaList(
        onSuccess: ((result: AllAreaListRespond) -> Unit)? = {

        },
        onFail: ((result: String) -> Unit)? = {
        }) {
        launchWithTry (whenTry = {
            val response = mCampService.campAllCityList(AllCityListParam().queryMap).request()
            if(response != null){
                if(response.isSuccess){
                    if (response.data != null){
                        if(response.data?.provinces != null){
                            response.data?.provinces?.sortByDescending { item -> item.sort }
                            response.data?.provinces?.add(0, wholeCountry)
                        }
                        if(response.data?.hot_cities != null){
                            response.data?.hot_cities?.sortByDescending { item -> item.sort }
                            response.data?.hot_cities?.add(0, wholeCountry)
                        }
                        if(response.data?.cities != null){
                            response.data?.cities?.sortByDescending { item -> item.sort }
                        }
                        areaData.value = response.data
                        val tempFilterAreaData = filterAreaData.value?:FilterAreaData()
                        tempFilterAreaData.historyList = historyCityList.value?.list?: mutableListOf()
                        tempFilterAreaData.provinces = response.data?.provinces?: mutableListOf()
                        tempFilterAreaData.hot_cities = response.data?.hot_cities?: mutableListOf()
                        tempFilterAreaData.cities = response.data?.cities?: mutableListOf()
                        filterAreaData.value = tempFilterAreaData
                    }
                    onSuccess?.invoke(response)
                } else {
                    onFail?.invoke(response.errorMsg?:"")
                }
            }

        }, whenCatch = {
            onFail?.invoke(it.toString())
        })
    }

    fun requestConditionList(
        onSuccess: ((result: CampListConditionListRespond) -> Unit)? = {
            if (it.data?.children != null){
                filterConditionData.postValue(it.data?.children)
            }
        },
        onFail: ((result: String) -> Unit)? = {
        }) {

        launchWithTry (whenTry = {
            val response = mCampService.campConditionTree(CampConditionTreeParam().apply {
                tree_id = 0
            }).request()
            if(response != null){
                if(response.isSuccess){
                    onSuccess?.invoke(response)
                } else {
                    onFail?.invoke(response.errorMsg?:"")
                }
            }
        }, whenCatch = {
            onFail?.invoke(it.toString())
        })
    }

    fun requestHotCondition(){
        launchWithTryAsynchronous(whenTry = {
            val respond = mCampService.campHotConditionList(CampHotConditionListParam().queryMap).request()
            respond?.let {
                hotConditionData.postValue(respond.data?.list)
            }
        })
    }

}